import { Application } from 'egg';
import { DataTypes, Model } from 'sequelize';

export interface FavoriteAttributes {
  id?: number;
  user_id: number;
  restaurant_id: number;
  created_at?: Date;
  updated_at?: Date;
}

export interface FavoriteInstance extends Model<FavoriteAttributes>, FavoriteAttributes {}

export default (app: Application) => {
  const { INTEGER, DATE } = DataTypes;

  const Favorite = app.model.define<FavoriteInstance>('Favorite', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    user_id: {
      type: INTEGER,
      allowNull: false,
      comment: '用户ID',
    },
    restaurant_id: {
      type: INTEGER,
      allowNull: false,
      comment: '美食店ID',
    },
    created_at: {
      type: DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
    updated_at: {
      type: DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
  }, {
    tableName: 'favorites',
    comment: '收藏表',
    indexes: [
      {
        unique: true,
        fields: ['user_id', 'restaurant_id'],
      },
    ],
  });

  // 关联关系
  (Favorite as any).associate = () => {
    app.model.Favorite.belongsTo(app.model.User, { foreignKey: 'user_id', as: 'user' });
    app.model.Favorite.belongsTo(app.model.Restaurant, { foreignKey: 'restaurant_id', as: 'restaurant' });
  };

  return Favorite;
};